<template>
  <div class="request-dashboard">
    <header class="mb-8">
      <h1 class="glow-text">请求管理</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <!-- 请求统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
      <div class="tech-card">
        <div class="text-light-dark mb-2">请求定义总数</div>
        <div class="text-3xl font-bold mb-2">{{ stats.totalDefinitions }}</div>
        <div class="text-sm text-light-dark">
          <span class="text-accent-blue">+{{ stats.newDefinitions }}</span> 本周新增
        </div>
      </div>

      <div class="tech-card">
        <div class="text-light-dark mb-2">执行次数</div>
        <div class="text-3xl font-bold mb-2">{{ stats.totalExecutions }}</div>
        <div class="text-sm text-light-dark">
          <span class="text-accent-blue">{{ stats.successRate }}%</span> 成功率
        </div>
      </div>

      <div class="tech-card">
        <div class="text-light-dark mb-2">平均响应时间</div>
        <div class="text-3xl font-bold mb-2">{{ stats.avgResponseTime }}ms</div>
        <div class="text-sm text-light-dark">
          <span :class="stats.responseTimeChange < 0 ? 'text-accent-blue' : 'text-accent-pink'">
            {{ stats.responseTimeChange > 0 ? '+' : '' }}{{ stats.responseTimeChange }}%
          </span> 
          较上周
        </div>
      </div>
    </div>

    <!-- 快速导航 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      <router-link to="/request/definitions" class="tech-card hover:border-primary transition-all duration-300">
        <div class="flex items-center mb-4">
          <svg class="w-6 h-6 mr-3 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
          </svg>
          <h3 class="text-xl font-medium">请求定义</h3>
        </div>
        <p class="text-light-dark mb-4">管理请求定义，包括创建、编辑、删除和执行请求定义。</p>
        <div class="text-primary">查看请求定义 →</div>
      </router-link>

      <router-link to="/request/definitions/create" class="tech-card hover:border-primary transition-all duration-300">
        <div class="flex items-center mb-4">
          <svg class="w-6 h-6 mr-3 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <h3 class="text-xl font-medium">创建请求</h3>
        </div>
        <p class="text-light-dark mb-4">创建新的请求定义，设置请求方法、URL、头信息和请求体。</p>
        <div class="text-primary">创建请求 →</div>
      </router-link>
    </div>

    <!-- 最近执行的请求 -->
    <div class="card">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-medium">最近执行的请求</h2>
        <router-link to="/request/definitions" class="btn btn-outline text-sm">查看全部</router-link>
      </div>

      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>

      <div v-else-if="recentExecutions.length === 0" class="text-center py-12 text-light-dark">
        暂无执行记录
      </div>

      <div v-else class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-dark-light">
              <th class="py-3 px-4 text-left">请求名称</th>
              <th class="py-3 px-4 text-left">方法</th>
              <th class="py-3 px-4 text-left">URL</th>
              <th class="py-3 px-4 text-left">状态码</th>
              <th class="py-3 px-4 text-left">响应时间</th>
              <th class="py-3 px-4 text-left">执行时间</th>
              <th class="py-3 px-4 text-left">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="execution in recentExecutions"
              :key="execution.id"
              class="border-b border-dark-light hover:bg-dark-darker"
            >
              <td class="py-3 px-4">{{ execution.name }}</td>
              <td class="py-3 px-4">
                <span :class="{
                  'badge badge-blue': execution.method === 'GET',
                  'badge badge-green': execution.method === 'POST',
                  'badge badge-purple': execution.method === 'PUT',
                  'badge badge-orange': execution.method === 'DELETE',
                  'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(execution.method)
                }">{{ execution.method }}</span>
              </td>
              <td class="py-3 px-4 font-mono text-sm truncate max-w-xs">{{ execution.url }}</td>
              <td class="py-3 px-4">
                <span :class="{
                  'text-accent-blue': execution.status_code < 300,
                  'text-accent-yellow': execution.status_code >= 300 && execution.status_code < 400,
                  'text-accent-orange': execution.status_code >= 400 && execution.status_code < 500,
                  'text-accent-pink': execution.status_code >= 500
                }">{{ execution.status_code }}</span>
              </td>
              <td class="py-3 px-4">{{ execution.response_time.toFixed(2) }} ms</td>
              <td class="py-3 px-4 text-light-dark">{{ formatTime(execution.executed_at) }}</td>
              <td class="py-3 px-4">
                <router-link :to="`/request/definitions/${execution.definition_id}`" class="text-primary hover:text-primary-light mr-2" title="查看定义">
                  <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                </router-link>
                <router-link :to="`/request/definitions/${execution.definition_id}/execute`" class="text-accent-blue hover:text-accent-blue/80" title="重新执行">
                  <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                  </svg>
                </router-link>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { requestApi } from '../../api';

// 状态变量
const loading = ref(false);

// 统计数据
const stats = ref({
  totalDefinitions: 0,
  newDefinitions: 0,
  totalExecutions: 0,
  successRate: 0,
  avgResponseTime: 0,
  responseTimeChange: 0
});

// 最近执行记录
const recentExecutions = ref<any[]>([]);

// 获取统计数据
const fetchStats = async () => {
  try {
    // 这里应该有一个获取统计数据的API，暂时使用模拟数据
    stats.value = {
      totalDefinitions: 24,
      newDefinitions: 5,
      totalExecutions: 128,
      successRate: 92.5,
      avgResponseTime: 78.3,
      responseTimeChange: -12.4
    };
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取最近执行记录
const fetchRecentExecutions = async () => {
  try {
    loading.value = true;
    
    // 这里应该有一个获取最近执行记录的API，暂时使用模拟数据
    recentExecutions.value = [
      {
        id: '1',
        definition_id: '101',
        name: '获取用户信息',
        method: 'GET',
        url: 'https://api.example.com/users/123',
        status_code: 200,
        response_time: 45.2,
        executed_at: new Date(Date.now() - 120000).toISOString()
      },
      {
        id: '2',
        definition_id: '102',
        name: '创建订单',
        method: 'POST',
        url: 'https://api.example.com/orders',
        status_code: 201,
        response_time: 78.5,
        executed_at: new Date(Date.now() - 180000).toISOString()
      },
      {
        id: '3',
        definition_id: '103',
        name: '更新支付状态',
        method: 'PUT',
        url: 'https://api.example.com/payments/456',
        status_code: 204,
        response_time: 32.1,
        executed_at: new Date(Date.now() - 240000).toISOString()
      },
      {
        id: '4',
        definition_id: '104',
        name: '删除用户',
        method: 'DELETE',
        url: 'https://api.example.com/users/789',
        status_code: 404,
        response_time: 12.8,
        executed_at: new Date(Date.now() - 300000).toISOString()
      },
      {
        id: '5',
        definition_id: '105',
        name: '获取订单状态',
        method: 'GET',
        url: 'https://api.example.com/orders/status',
        status_code: 500,
        response_time: 156.3,
        executed_at: new Date(Date.now() - 360000).toISOString()
      }
    ];
  } catch (error) {
    console.error('获取最近执行记录失败:', error);
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchStats(),
    fetchRecentExecutions()
  ]);
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
